import React, { useMemo, useState } from 'react';
import styles from './index.less';
import DayItem from './DayItem';
import moment, { Moment } from 'moment';

const MyCalendar: React.FC<{
  initDay?: string | number | Moment;
  onChange?: (day: Moment) => void;
}> = ({ initDay, onChange }) => {
  const [curMoment, setCurMoment] = useState<Moment>(moment(initDay));
  const [curYear, curMon, curDay] = useMemo(() => {
    return [curMoment.year(), curMoment.month(), curMoment.date()];
  }, [curMoment]);

  const renderWeekItems = () => {
    const weeks = ['日', '一', '二', '三', '四', '五', '六'];
    return weeks.map((text) => {
      return (
        <span className={styles.week} key={text}>
          {text}
        </span>
      );
    });
  };

  const onChangeDay = (day: Moment) => {
    setCurMoment(day);
    onChange?.(day);
  };

  const changeMonth = (type: 'pre' | 'next') => {
    switch (type) {
      case 'pre':
        return onChangeDay(moment(curMoment).subtract(1, 'month'));
      case 'next':
        return onChangeDay(moment(curMoment).add(1, 'month'));
      default:
        return null;
    }
  };
  const renderDateItems = () => {
    // 当月第一个日期开始时间
    const firstDate = moment(curMoment).startOf('month').startOf('week');
    // 当月最后一个日期的最后时间
    const lastDate = moment(curMoment).endOf('month').endOf('week');
    const arr = [];
    while (firstDate < lastDate) {
      arr.push(moment(firstDate));
      firstDate.add(1, 'day');
    }
    return arr.map((item) => {
      let type: 'normal' | 'active' | 'gray' = 'normal';
      if (curMoment.isSame(item, 'date')) {
        type = 'active';
      } else if (curMoment.month() !== item.month()) {
        type = 'gray';
      }
      return <DayItem day={item} type={type} key={item.format()} onClick={onChangeDay} />;
    });
  };

  return (
    <div className={styles.myCalendarWrapper}>
      <div className={styles.header}>
        <span className={styles.leftArrow + ' ' + styles.Arrow} onClick={() => changeMonth('pre')}>
          &lt;
        </span>
        <div className={styles.title}>{`${curYear}年${curMon}月`}</div>
        <span
          className={styles.rightArrow + ' ' + styles.Arrow}
          onClick={() => changeMonth('next')}
        >
          &gt;
        </span>
      </div>
      <div className={styles.weekHeader}>{renderWeekItems()}</div>
      <div className={styles.dayContent}>{renderDateItems()}</div>
    </div>
  );
};

export default MyCalendar;
